package vn.com.vega.music.view.adapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.ActivityBase;
import vn.com.vega.chacha.v2.Appinstant;
import vn.com.vega.chacha.v2.SelecSongPlay;
import vn.com.vega.chacha.v2.Asynctask.DoSomthingListener;
import vn.com.vega.chacha.v2.Asynctask.FavoriteSong;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.downloadmanager.DownloadStatusListener;
import vn.com.vega.music.downloadmanager.DownloadUtil;
import vn.com.vega.music.downloadmanager.EventNotifier;
import vn.com.vega.music.objects.Playlist;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.PlaylistUtil;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.adapter.base.AutoLoadingAdapter.AutoLoadingInterface;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

public class SongListAdapter extends BaseAdapter implements
		DownloadStatusListener, Const, SectionIndexer, AutoLoadingInterface {
	protected Hashtable<Integer, Integer> hashSongProgress = new Hashtable<Integer, Integer>();
	protected Hashtable<Integer, Integer> hashSongPosition = new Hashtable<Integer, Integer>();

	private Activity mContext;
	private LayoutInflater mInflater;
	private List<Object> mListObject = new ArrayList<Object>();

	protected static Integer firstVisibleItem;
	protected static Integer lastVisibleItem;
	protected static boolean isScrolling = false;

	private SongListAdapter songListAdapter;
	private DataStore dataStore;

	private boolean isLocalMusic = false;

	private String listenerKey;

	HashMap<String, Integer> azIndexer;
	String[] sections;
	private Song currentPlay = null;

	private View mCurrentMenuShow = null;
	private Toast mToast;
	private boolean isChart = false;

	public void setChart(boolean isChart) {
		this.isChart = isChart;
	}

	public class customComparator implements Comparator<Object> {
		public int compare(Object object1, Object object2) {
			if (object1 instanceof Song && object2 instanceof Song) {
				Song song1 = (Song) object1;
				Song song2 = (Song) object2;
				return song1.title.toUpperCase().trim()
						.compareTo(song2.title.toUpperCase().trim());
			}
			return 0;
		}
	}

	private void showToast(String mess) {
		if (mContext instanceof ActivityBase) {
			ActivityBase act = (ActivityBase) mContext;
			act.showToast(mess);
			return;
		}
		if (mToast == null) {
			mToast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);
		}
		mToast.setText(mess);
		mToast.show();
	}

	public SongListAdapter(Activity context, List<Object> objects,
			boolean _isLocalMusic, String key) {
		mContext = context;
		isLocalMusic = _isLocalMusic;
		listenerKey = key;
		dataStore = DataStore.getInstance();
		songListAdapter = this;
		// mInflater = LayoutInflater.from(context);
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (isLocalMusic) {
			// mListObject.clear();
			// mListObject.addAll(objects);
			mListObject = objects;
			if (mListObject.size() > 0) {
				Object obj = mListObject.get(0);
				if (obj instanceof Song)
					indexData();
			}

		} else {
			// DownloadManager.addDownloadStatusListener(listenerKey,
			// songListAdapter);

			if (objects != null) {
				mListObject = objects;
				// for (Object object : objects) {
				// if (object instanceof Song) {
				// Song cached = dataStore.getSongById(((Song) object).id);
				// if (cached != null) {
				// mListObject.add(cached);
				// continue;
				// }
				// }
				// mListObject.add(object);
				// }
			}
			// DowloadUtil.bindToService(mContext);
		}
		currentPlay = Util.getCurrentSongPlay();
	}

	public void setData(List<Object> objs) {
		mListObject = objs;
	}

	public void indexData() {
		// Collections.sort(mListObject, new customComparator());
		azIndexer = new HashMap<String, Integer>();
		int size = mListObject.size();
		for (int i = 0; i < size; i++) {
			Object obj = mListObject.get(i);
			if (obj instanceof Song) {
				Song song = (Song) obj;
				String element = song.title.trim();
				// We store the first letter of the word, and its index.
				azIndexer.put(element.substring(0, 1).toUpperCase(), i);
			}

		}
		Set<String> keys = azIndexer.keySet(); // set of letters

		Iterator<String> it = keys.iterator();
		ArrayList<String> keyList = new ArrayList<String>();

		while (it.hasNext()) {
			String key = it.next();
			keyList.add(key);
		}
		Collections.sort(keyList);// sort the keylist
		sections = new String[keyList.size()]; // simple conversion to
												// array
		for (int i = 0; i < keyList.size(); i++) {
			sections[i] = keyList.get(i);
		}
	}

	@Override
	public int getCount() {
		return mListObject.size();
	}

	@Override
	public Object getItem(int position) {
		return mListObject.get(position);
	}

	public void setIsLocalMusic(boolean value) {
		isLocalMusic = value;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;

		Object obj = mListObject.get(position);

		if (convertView == null) {
			if (isChart) {
				convertView = mInflater.inflate(R.layout.song_chart_item, null);

				holder = new ViewHolder();
				holder.songChartIndex = (TextView) convertView
						.findViewById(R.id.tv_song_chart_index);
				holder.title = (TextView) convertView
						.findViewById(R.id.tv_song_title);
				holder.arstist = (TextView) convertView
						.findViewById(R.id.tv_artist_name);
				holder.countListen = (TextView) convertView
						.findViewById(R.id.tv_count_song_listen);
				// holder.progressbar = (ProgressBar)
				// convertView.findViewById(R.id.download_progressbar);
				holder.mShowHideMenu = (LinearLayout) convertView
						.findViewById(R.id.layout_show_hide_menu_song_item);
				holder.mShowHideMenu
						.setOnClickListener(onMenuShowClickListener);
				holder.menuLayout = (LinearLayout) convertView
						.findViewById(R.id.layout_menus_song_item);
				holder.insertToNowPlaying = (ImageButton) convertView
						.findViewById(R.id.bt_insert_to_now_playing);
				holder.insertToNowPlaying
						.setOnClickListener(onInsertToNowPlayingListener);
				holder.addToPlaylist = (ImageButton) convertView
						.findViewById(R.id.bt_add_to_playlist);
				holder.addToPlaylist
						.setOnClickListener(onAddToPlaylistListener);
				holder.downloadSong = (ImageButton) convertView
						.findViewById(R.id.bt_dowload_song);
				holder.downloadSong.setOnClickListener(onDownloadClickListener);
				holder.likeSong = (ImageButton) convertView
						.findViewById(R.id.bt_like_song);
				holder.likeSong.setOnClickListener(onLikeSongListener);
				holder.rington = (ImageButton) convertView
						.findViewById(R.id.bt_rington);
				holder.rington.setOnClickListener(onRingtoneListener);
				holder.share = (ImageButton) convertView
						.findViewById(R.id.bt_share_song);
				holder.share.setOnClickListener(onShareClickListener);
				holder.songItem = convertView
						.findViewById(R.id.layout_song_item);
				holder.songItem.setOnClickListener(openSongClickListener);

				convertView.setTag(holder);
			} else {
				convertView = mInflater.inflate(R.layout.song_item, null);

				holder = new ViewHolder();
				holder.title = (TextView) convertView
						.findViewById(R.id.tv_song_title);
				holder.arstist = (TextView) convertView
						.findViewById(R.id.tv_artist_name);
				holder.countListen = (TextView) convertView
						.findViewById(R.id.tv_count_song_listen);
				// holder.progressbar = (ProgressBar)
				// convertView.findViewById(R.id.download_progressbar);
				holder.mShowHideMenu = (LinearLayout) convertView
						.findViewById(R.id.layout_show_hide_menu_song_item);
				holder.mShowHideMenu
						.setOnClickListener(onMenuShowClickListener);
				holder.menuLayout = (LinearLayout) convertView
						.findViewById(R.id.layout_menus_song_item);
				holder.insertToNowPlaying = (ImageButton) convertView
						.findViewById(R.id.bt_insert_to_now_playing);
				holder.insertToNowPlaying
						.setOnClickListener(onInsertToNowPlayingListener);
				holder.addToPlaylist = (ImageButton) convertView
						.findViewById(R.id.bt_add_to_playlist);
				holder.addToPlaylist
						.setOnClickListener(onAddToPlaylistListener);
				holder.downloadSong = (ImageButton) convertView
						.findViewById(R.id.bt_dowload_song);
				holder.downloadSong.setOnClickListener(onDownloadClickListener);
				holder.likeSong = (ImageButton) convertView
						.findViewById(R.id.bt_like_song);
				holder.likeSong.setOnClickListener(onLikeSongListener);
				holder.rington = (ImageButton) convertView
						.findViewById(R.id.bt_rington);
				holder.rington.setOnClickListener(onRingtoneListener);
				holder.share = (ImageButton) convertView
						.findViewById(R.id.bt_share_song);
				holder.share.setOnClickListener(onShareClickListener);
				holder.songItem = convertView
						.findViewById(R.id.layout_song_item);
				holder.songItem.setOnClickListener(openSongClickListener);

				convertView.setTag(holder);
			}

		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		if (obj instanceof Song) {
			final Song song = (Song) obj;
			if (isChart) {
				String index;
				if (position < 9) {
					index = "0" + (position + 1) + ".";
				} else {
					index = (position + 1) + ".";
				}
				holder.songChartIndex.setText(index);
				if (position < 3) {
					holder.songChartIndex.setTextColor(Color
							.parseColor("#8FC53D"));
				} else {
					holder.songChartIndex.setTextColor(Color
							.parseColor("#CCCCCC"));
				}
			}

			holder.title.setText(song.title);
			if (currentPlay == null) {
				holder.title.setTextColor(Color.parseColor("#175893"));
				if (!isChart) {
					holder.title.setCompoundDrawablesWithIntrinsicBounds(
							mContext.getResources().getDrawable(
									R.drawable.ic_left_song_item_nomal), null,
							null, null);
				}
			} else {
				boolean isCurrenPlay = false;
				if (song.isAvailableLocally()) {
					if (song.cached_file_path
							.equals(currentPlay.cached_file_path)) {
						isCurrenPlay = true;
					} else {
						isCurrenPlay = false;
					}
				} else {
					if (song.id == currentPlay.id) {
						isCurrenPlay = true;
					} else {
						isCurrenPlay = false;
					}
				}

				if (isCurrenPlay) {
					holder.title.setTextColor(Color.parseColor("#E04624"));
					if (!isChart) {
						holder.title.setCompoundDrawablesWithIntrinsicBounds(
								mContext.getResources().getDrawable(
										R.drawable.ic_left_song_item_played),
								null, null, null);
					}
				} else {
					holder.title.setTextColor(Color.parseColor("#175893"));
					if (!isChart) {
						holder.title.setCompoundDrawablesWithIntrinsicBounds(
								mContext.getResources().getDrawable(
										R.drawable.ic_left_song_item_nomal),
								null, null, null);
					}
				}
			}
			if (song.isFavorite) {
				holder.likeSong.setSelected(true);
			} else {
				holder.likeSong.setSelected(false);
			}
			if (song.isLocalSong()) {
				holder.downloadSong.setVisibility(View.GONE);
				holder.likeSong.setVisibility(View.GONE);
				holder.share.setVisibility(View.GONE);
				holder.addToPlaylist.setVisibility(View.GONE);
				holder.countListen.setVisibility(View.GONE);
			} else {
				if (!Util.checkStringIsemptyOrNull(song.cached_file_path)) {
					holder.downloadSong.setVisibility(View.GONE);
//					holder.likeSong.setVisibility(View.GONE);
				} else {
					holder.downloadSong.setVisibility(View.VISIBLE);
				}
				holder.likeSong.setVisibility(View.VISIBLE);
				holder.share.setVisibility(View.VISIBLE);
				holder.addToPlaylist.setVisibility(View.VISIBLE);
				holder.countListen.setVisibility(View.VISIBLE);
			}
			holder.mShowHideMenu.setTag(holder.menuLayout);
			holder.likeSong.setTag(song);
			holder.downloadSong.setTag(song);

			holder.addToPlaylist.setTag(song);
			holder.insertToNowPlaying.setTag(song);
			holder.share.setTag(song);
			holder.rington.setTag(song);
			holder.songItem.setTag(Integer.valueOf(position));

			holder.menuLayout.setVisibility(View.GONE);
			// holder.thumb.setTag(song);
			// setOnThumbClick(holder.thumb);
			hashSongPosition.put(song.id, position);

			if (isLocalMusic) {
				// holder.thumb.setBackgroundResource(R.drawable.ic_listview_downloaded);
				// holder.thumb.setEnabled(false);

				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				params.addRule(RelativeLayout.CENTER_IN_PARENT);
				// holder.thumb.setLayoutParams(params);

				holder.arstist.setVisibility(TextView.VISIBLE);
				holder.countListen.setVisibility(View.GONE);
				holder.arstist.setText(String.format(
						mContext.getString(R.string.format_by),
						song.artist_name));

				// holder.progressbar.setVisibility(ProgressBar.GONE);
			} else if (song.isAvailableLocally()
					/*|| dataStore.isAvailableAtLocal(song.id)*/) {
				// thumbnail with downloaded symbol
				// holder.thumb.setBackgroundResource(R.drawable.ic_listview_downloaded);
				// holder.thumb.setEnabled(false);

				holder.arstist.setVisibility(TextView.VISIBLE);
				holder.countListen.setVisibility(View.GONE);
				// holder.view.setText(String.format(mContext.getString(R.string.format_view_count),
				// song.viewCount));
				holder.arstist.setText(String.format(
						mContext.getString(R.string.format_by),
						song.artist_name));

				// holder.progressbar.setVisibility(ProgressBar.GONE);
			} else {
				Integer progress = hashSongProgress.get(song.id);
				if (progress == null) {
					if (song.isWaitToDownload()) {
						// holder.thumb.setBackgroundResource(R.drawable.ic_listview_downloading);
						// holder.thumb.setEnabled(true);

						holder.arstist.setVisibility(TextView.VISIBLE);
						holder.countListen.setVisibility(View.INVISIBLE);
						holder.arstist.setText(song.artist_name
								+ " - Đang đợi tải");

						// holder.progressbar.setVisibility(ProgressBar.GONE);
					} else {
						// holder.thumb.setBackgroundResource(R.drawable.ic_listview_not_downloaded);
						// holder.thumb.setEnabled(true);
						holder.arstist.setVisibility(TextView.VISIBLE);
						holder.countListen.setVisibility(View.VISIBLE);

						holder.countListen.setText(song.viewCount + "");
						holder.arstist.setText(song.artist_name);

						// holder.progressbar.setVisibility(ProgressBar.GONE);
					}
					// connecting status
				} else if (progress == CONNECTING_VALUE) {
					// holder.thumb.setBackgroundResource(R.drawable.ic_listview_downloading);
					// holder.thumb.setEnabled(false);

					holder.arstist.setVisibility(TextView.VISIBLE);
					holder.countListen.setVisibility(View.INVISIBLE);
					holder.arstist.setText(R.string.connecting);

					// holder.progressbar.setVisibility(ProgressBar.GONE);
					// waiting status
				} else if (progress == WAITING_VALUE) {
					// holder.thumb.setBackgroundResource(R.drawable.ic_listview_downloading);
					// holder.thumb.setEnabled(true);

					holder.arstist.setVisibility(TextView.VISIBLE);
					holder.countListen.setVisibility(View.INVISIBLE);
					holder.arstist
							.setText(song.artist_name + " - Đang đợi tải");

					// holder.progressbar.setVisibility(ProgressBar.GONE);
				} else if (progress > CONNECTING_VALUE
						&& progress < DOWNLOADED_VALUE) {
					// holder.progressbar.setVisibility(ProgressBar.VISIBLE);
					// holder.progressbar.setProgress(progress);
					// holder.thumb.setBackgroundResource(R.drawable.ic_listview_downloading);
					// holder.thumb.setEnabled(false);

					holder.arstist.setVisibility(TextView.VISIBLE);
					holder.countListen.setVisibility(View.INVISIBLE);
					holder.arstist.setText("(" + progress + " %) - "
							+ song.artist_name);
				}
			}
		}
		return convertView;
	}

	View.OnClickListener openSongClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int index = ((Integer) v.getTag()).intValue();
			openListSong(getSongList(), index);
		}
	};

	private void openListSong(List<Song> listSong, int index) {
		// if (currentPlay == null || currentPlay.id != listSong.get(index).id)
		// {
//		currentPlay = listSong.get(index);
//		notifyDataSetChanged();
		// }
		Util.openListSong(listSong, index, mContext);
	}

	View.OnClickListener onMenuShowClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			View menuLayout = (View) v.getTag();
			if (mCurrentMenuShow == menuLayout) {
				if (menuLayout.isShown()) {
					menuLayout.setVisibility(View.GONE);
				} else {
					menuLayout.setVisibility(View.VISIBLE);
				}
			} else {
				if (mCurrentMenuShow != null) {
					mCurrentMenuShow.setVisibility(View.GONE);
				}
				menuLayout.setVisibility(View.VISIBLE);
				mCurrentMenuShow = menuLayout;
			}
		}
	};

	View.OnClickListener onDownloadClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			hideMenu();
			Song song = (Song) v.getTag();
//			if (dataStore.songIsDownloaded(song)) {
//				showToast("Bài hát đã được tải về");
//				return;
//			}
			if (DownloadUtil.checkSongIsInListDownload(song)) {
				showToast("Bài hát đã được thêm vào danh sách tải về");
				return;
			}
			DownloadUtil.downloadSong(song, mContext);
		}
	};

	View.OnClickListener onInsertToNowPlayingListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			hideMenu();
			Song song = (Song) v.getTag();
			if (Util.insertSongToNowPlaying(song, mContext)) {
				showToast(mContext
						.getString(R.string.insert_to_now_playing_success));
			} else {
				showToast(mContext
						.getString(R.string.insert_to_now_playing_fail));
			}

		}
	};

	View.OnClickListener onAddToPlaylistListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			hideMenu();
			Song song = (Song) v.getTag();
			if (mContext instanceof ActivityBase) {
				ActivityBase act = (ActivityBase) mContext;
				List<Song> listSong = new ArrayList<Song>();
				listSong.add(song);
				PlaylistUtil.addSongToPlaylist(listSong, act);
			}
		}
	};

	DoSomthingListener doLikeSongListener = new DoSomthingListener() {

		@Override
		public void startDoSomthing(List<Object> extractObject) {
			// TODO Auto-generated method stub
			String message = (String) extractObject.get(0);
			showToast(message);
		}

		@Override
		public void doSomethingSuccess(List<Object> extractObject) {
			// TODO Auto-generated method stub
			String message = (String) extractObject.get(1);
			if (!Util.checkStringIsemptyOrNull(message)) {
				showToast(message);
			}
			notifyDataSetChanged();

		}

		@Override
		public void doSomethingFail(List<Object> extractObject) {
			// TODO Auto-generated method stub
			String errorMessage = (String) extractObject.get(1);
			if (!Util.checkStringIsemptyOrNull(errorMessage)) {
				showToast(errorMessage);
			}
		}
	};
	View.OnClickListener onLikeSongListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			hideMenu();
			Song song = (Song) v.getTag();
			if (mContext instanceof ActivityBase) {
				FavoriteSong favoriteSong;
				if (song.isFavorite) {
					favoriteSong = new FavoriteSong((ActivityBase) mContext,
							song, doLikeSongListener, false);
				} else {
					favoriteSong = new FavoriteSong((ActivityBase) mContext,
							song, doLikeSongListener, true);
				}
				favoriteSong.execute();
			}

			// Playlist favPlaylist = dataStore
			// .getSpecialPlaylistByType(Playlist.TYPE_FAVORITE);
			// // if (favPlaylist == null) {
			// showToast("không thành công");
			// } else {
			// if (dataStore.songIsLiked(song)) {
			// dataStore.removeSongFromPlaylist(favPlaylist.id, song.id);
			// dataStore.removeSongFromLiked(song);
			// v.setSelected(false);
			// showToast("Bỏ thích thành công");
			// } else {
			// // add song first
			// if (dataStore.addSong(song)) {
			// if (dataStore
			// .addSongToPlaylist(favPlaylist.id, song.id)) {
			// dataStore.addSongToListSongLiked(song);
			// v.setSelected(true);
			// showToast("Đã thêm vào danh sách nhạc yêu thích");
			// } else {
			// showToast("không thành công");
			// }
			//
			// } else {
			// showToast("không thành công");
			// }
			// }
			// }
		}
	};

	View.OnClickListener onRingtoneListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			hideMenu();
			Song song = (Song) v.getTag();
			Appinstant app = (Appinstant) mContext.getApplication();
			app.showListRingtone(mContext, song.title);
		}
	};

	View.OnClickListener onShareClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			hideMenu();
			Song song = (Song) v.getTag();
			Util.share(song.shareMessage, mContext);
		}
	};

	// private boolean checkForSure(Playlist pl, Song s) {
	// boolean result = false;
	// for (Song song : pl.getSongList()) {
	// if (song.id == s.id) {
	// result = true;
	// break;
	// }
	// }
	// return result;
	// }

	// private boolean songInFavorite(Song song) {
	// if (song == null) {
	// return false;
	// }
	// Playlist favPlaylist = dataStore
	// .getSpecialPlaylistByType(Playlist.TYPE_FAVORITE);
	// if (favPlaylist == null) {
	// return false;
	// }
	// if (favPlaylist.getSongList().contains(song)
	// || checkForSure(favPlaylist, song)) {
	// return true;
	// } else {
	// return false;
	// }
	// }

	private void hideMenu() {
		if (mCurrentMenuShow != null) {
			mCurrentMenuShow.setVisibility(View.GONE);
		}
	}

	protected void askGoToOnline() {
		// show Confirm dialog
		// TabHolder.getTabHolder().askGoToOnline();
	}

//	public void download(Song song) {
//		if (dataStore.isInOfflineMode()) {
//			askGoToOnline();
//			return;
//		}
//
//		DownloadManager.removeDownloadStatusListener(listenerKey);
//
//		DownloadManager.addDownloadStatusListener(listenerKey, songListAdapter);
//
//		if (NetworkStatusReceiver.isConnected()) {
//
//			dataStore.addSong(song);
//
//			// song is waiting to download, remove it
//			if (song.isWaitToDownload()) {
//				dataStore.removeSongFromSongDownloadPool(song.id);
//				// to show normal thumbnail
//				hashSongProgress.remove(song.id);
//				// refresh listview
//				notifyDataSetChanged();
//				// song is normal state
//			} else {
//				if (DownloadManager.isRunning()) {
//					if (dataStore.addSongToSongDownloadPool(song.id)) {
//						// indicate this song is waiting to download
//						hashSongProgress.put(song.id, WAITING_VALUE);
//						// refresh listview
//						notifyDataSetChanged();
//					}
//				} else {
//					// to show connecting message
//					hashSongProgress.put(song.id, CONNECTING_VALUE);
//					// refresh listview
//					notifyDataSetChanged();
//					// for simple i should clear all download pool before start
//					dataStore.clearSongDownloadPool();
//					dataStore.clearPlaylistDownloadPool();
//					// add song to song download pool
//					dataStore.addSongToSongDownloadPool(song.id);
//					// start download thread
//					DownloadManager.startDownload();
//				}
//			}
//		} else {
//			Toast.makeText(mContext.getApplicationContext(),
//					"Không có kết nối mạng", Toast.LENGTH_LONG).show();
//		}
//	}

	/**
	 * addedToDownloadPool Use to record which song is added to download pool by
	 * this adapter Remember, song may be added by this adapter, may be added by
	 * another
	 */
//	private Hashtable<Integer, Integer> addedToDownloadPool = new Hashtable<Integer, Integer>();

	/**
	 * This function is used to remove all song from download which we added to
	 * download pool last time
	 * 
	 * HEY, don't touch the download manager, it will automatically stop if
	 * download pool is empty
	 * 
	 * @author Ngo Tri Hoai
	 */
//	public void removeAllAddedSongFromDownloadPool() {
//		List<Song> songList = getSongList();
//		if (songList == null) {
//			return;
//		}
//
//		boolean removed = false;
//		for (Song song : songList) {
//			if (addedToDownloadPool.containsKey(song.id)) {
//				removed = true;
//				addedToDownloadPool.remove(song.id);
//				dataStore.removeSongFromSongDownloadPool(song.id);
//			}
//		}
//
//		if (removed) {
//			notifyDataSetChanged();
//		}
//	}

//	public void onPause() {
//		DownloadManager.removeDownloadStatusListener(listenerKey);
//	}

//	public void onResume() {
//		DownloadManager.addDownloadStatusListener(listenerKey, songListAdapter);
//		notifyDataSetChanged();
//	}

	/**
	 * This function is used to add all song into download pool if needed and
	 * remember which song is added, so we can remove them later
	 * 
	 * HEY, remember to start downloadmanager if it's not running !
	 * 
	 * @author Ngo Tri Hoai
	 */
//	public void downloadAll() {
//		if (NetworkStatusReceiver.isConnected()) {
////			DownloadManager.removeDownloadStatusListener(listenerKey);
//
////			DownloadManager.addDownloadStatusListener(listenerKey,
////					songListAdapter);
//
//			List<Song> songList = getSongList();
//			if (songList == null) {
//				return;
//			}
//
//			boolean added = false;
//			for (Song song : songList) {
////				dataStore.addSong(song);
////				Song cached = dataStore.getSongById(song.id);
//				if (!cached.isAvailableLocally() || !cached.isWaitToDownload()) {
//					added = true;
//					dataStore.addSongToSongDownloadPool(song.id);
//					hashSongProgress.put(song.id, WAITING_VALUE);
//					addedToDownloadPool.put(song.id, song.id);
//				}
//			}
//
//			if (added) {
//				notifyDataSetChanged();
//				if (!DownloadManager.isRunning())
//					DownloadManager.startDownload();
//			}
//		} else {
//			Toast.makeText(mContext.getApplicationContext(),
//					"Không có kết nối mạng", Toast.LENGTH_LONG).show();
//		}
//
//	}

//	public void cancelDownload() {
//		DownloadManager.removeDownloadStatusListener(listenerKey);
//		hashSongProgress.clear();
//		if (dataStore.removeSongsFromSongDownloadPool(getSongList()) > 0)
//			notifyDataSetInvalidated();
//	}

	class ViewHolder {
		TextView title;
		TextView arstist, countListen;
		LinearLayout menuLayout;
		LinearLayout mShowHideMenu;
		TextView songChartIndex;
		View songItem;
		// ProgressBar progressbar;
		ImageButton insertToNowPlaying, addToPlaylist, downloadSong, likeSong,
				rington, share;
	}

	public void notifyListObjectChanged(List<Object> objectsChanged) {
		notifyListObjectChanged(objectsChanged, TYPE_LIST_ADDED);
	}

	public void notifyListObjectChanged(List<Object> objectsChanged, int type) {
		if (objectsChanged != null) {
			if (type == TYPE_LIST_REPLACED)
				mListObject.clear();
			mListObject.addAll(objectsChanged);
			notifyDataSetChanged();
		}
	}

	public ArrayList<Song> getSongList() {
		ArrayList<Song> result = new ArrayList<Song>();
		for (Object obj : mListObject) {
			if (obj instanceof Song) {
				result.add((Song) obj);
			}
		}
		return result;
	}

	public void onSongDownloadStart(Song song) {

		if (!isScrolling) {
			Integer _position = hashSongPosition.get(song.id);
			if (_position >= firstVisibleItem && _position <= lastVisibleItem) {
				hashSongProgress.put(song.id, CONNECTING_VALUE);
				notifyDataSetChanged();
			}
		}
	}

	// private void setOnThumbClick(View v) {
	// v.setOnClickListener(new OnClickListener() {
	// @Override
	// public void onClick(View v) {
	//
	// if (mContext instanceof AbstractSongAcitivity) {
	// AbstractSongAcitivity thumClick = (AbstractSongAcitivity) mContext;
	// thumClick.onThumbnailClickListener(v);
	// }
	// }
	// });
	// }

	@Override
	public void onSongDownloadDone(Song song) {
		hashSongProgress.remove(song.id);
		notifyDataSetChanged();
	}

	@Override
	public void onSongDownloadProgress(Song sg, int total, int downloaded) {

		if (!isScrolling) {
			Integer _position = hashSongPosition.get(sg.id);
			if (_position >= firstVisibleItem && _position <= lastVisibleItem) {
				int _currStatus = (int) ((downloaded * 100) / total);
				hashSongProgress.put(sg.id, _currStatus);
				notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onSongDownloadError(Song sg, int errorCode) {
		if (errorCode == EventNotifier.ERROR_NONE) {
			return;
		}

		if (errorCode == EventNotifier.ERROR_POSTPONED) {
			hashSongProgress.put(sg.id, WAITING_VALUE);
		} else {
			hashSongProgress.remove(sg.id);
		}
		notifyDataSetChanged();

		if (errorCode == EventNotifier.ERROR_SAVING_FAILED) {
			Toast.makeText(mContext,
					R.string.my_playlist_download_error_diskfull,
					Toast.LENGTH_LONG).show();
		} else if (errorCode != EventNotifier.ERROR_POSTPONED) {
			Toast.makeText(mContext,
					R.string.my_playlist_download_error_network,
					Toast.LENGTH_LONG).show();
		}

	}

	public void onPlaylistDownloadStart(Playlist playlist) {
	}

	@Override
	public void onPlaylistDownloadDone(Playlist pl) {
	}

	@Override
	public void onPlaylistDownloadProgress(Playlist pl, int totalSong,
			int downloadedSong) {
	}

	public void onDownloadStart(int total) {
	}

	@Override
	public void onDownloadProgress(int totalSong, int downloadedSong) {
	}

	@Override
	public void onDownloadStopped() {
		hashSongProgress.clear();
		notifyDataSetChanged();

//		if (DownloadManager.isLastSongError()) {
//			Toast.makeText(mContext, R.string.my_playlist_download_stopped,
//					Toast.LENGTH_SHORT).show();
//		} else {
//			if ((dataStore.getSongDownloadPool().size() > 0)) {
//				// Toast.makeText(mContext,
//				// R.string.my_playlist_download_stopped,
//				// Toast.LENGTH_SHORT).show();
//			} else {
//				// Toast.makeText(mContext,
//				// R.string.my_playlist_download_completed,
//				// Toast.LENGTH_SHORT).show();
//			}
//		}
	}

	public static void setVisibleItems(int _firstVisibleItem,
			int _lastVisibleItem) {
		firstVisibleItem = _firstVisibleItem;
		lastVisibleItem = _lastVisibleItem;
	}

	public static void setScrolling(boolean _isScrolling) {
		isScrolling = _isScrolling;
	}

	@Override
	public int getPositionForSection(int section) {
		// TODO Auto-generated method stub
		String letter = sections[section];
		return azIndexer.get(letter);
	}

	@Override
	public int getSectionForPosition(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Object[] getSections() {
		// TODO Auto-generated method stub
		return sections;
	}

	@Override
	public void onDownloadInOfflineMode() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDownloadVia3gDisable() {
		// TODO Auto-generated method stub

	}

	public void setCurrentPlay(Song song) {
		if (currentPlay == null && song == null) {
			return;
		}
		if (currentPlay == null || song == null || currentPlay.id != song.id) {
			currentPlay = song;
			notifyDataSetChanged();
		} else {
			// do no thing
		}
	}

	public void playAllSong(String listSongName) {
		if (mContext instanceof ActivityBase) {
			ActivityBase act = (ActivityBase) mContext;
			act.trackEvent("Select item", "Play all song", listSongName, 1);
			List<Song> listSong = new ArrayList<Song>();
			for (Object object : mListObject) {
				Song song = (Song) object;
				listSong.add(song);
			}
			Util.openListSong(listSong, 0, (Activity) mContext);
		}
	}

	public void selectSongPlay(String listSongName) {
		if (mContext instanceof ActivityBase) {
			Activity act = (Activity) mContext;
			Intent selectSong = new Intent(act, SelecSongPlay.class);
			List<Song> list = new ArrayList<Song>();
			for (int i = 0; i < mListObject.size(); i++) {
				list.add((Song) mListObject.get(i));
			}
			Appinstant mApp = (Appinstant) act.getApplication();
			mApp.tranportString.put(SelecSongPlay.KEY_LIST_SONG_TITLE, listSongName);
			
			mApp.tranportListSong.put(listSongName, list);
			selectSong.putExtra(SelecSongPlay.KEY_LIST_SONG, listSongName);
			
			act.startActivity(selectSong);
		}

	}
}
